﻿#include"XQTimerTask.h"
#include<QDateTime>
#include<QDebug>
XQTimerTask::XQTimerTask(qint64 sec, std::function<void()> task)
	:m_runTime(QDateTime::currentDateTime()),m_timerSec(sec), m_task([=](XQTimerTask*) {task(); })
{
}

XQTimerTask::XQTimerTask(QDateTime startTime, qint64 sec, std::function<void()> task)
	:m_runTime(startTime), m_timerSec(sec), m_task([=](XQTimerTask*) {task(); })
{
}

XQTimerTask::XQTimerTask(QDateTime runTime, qint64 count, qint64 sec, std::function<void()> task)
	:m_runTime(runTime),m_count(count), m_timerSec(sec), m_task([=](XQTimerTask*) {task(); })
{
}

XQTimerTask::XQTimerTask(QDateTime runTime, qint64 count, qint64 sec, std::function<void()> task, bool mainThread)
	:m_runTime(runTime), m_count(count), m_timerSec(sec), m_task([=](XQTimerTask*) {task(); }),m_mainThreadRun(mainThread)
{
}

XQTimerTask::XQTimerTask(QDateTime runTime, qint64 count, std::function<QDateTime(XQTimerTask*)> upTimeFunc, std::function<void()> task, bool mainThread)
	:m_runTime(runTime), m_count(count), m_upTimeFunc(upTimeFunc), m_task([=](XQTimerTask*) {task(); }), m_mainThreadRun(mainThread)
{
}

bool XQTimerTask::isEnabled() const
{
	return m_enable;
}

bool XQTimerTask::isRunTask() const
{
	return (!isCountFinish())&&isTimeOut();
}

bool XQTimerTask::isTimeOut() const
{
	//qDebug() << QDateTime::currentDateTime().secsTo(m_runTime);
	if(QDateTime::currentDateTime().secsTo(m_runTime)<0)
	{
		return true;
	}
	return false;
}

bool XQTimerTask::isCountFinish() const
{
	return m_count==0;
}

bool XQTimerTask::isMainThreadRun() const
{
	return m_mainThreadRun;
}

qint64 XQTimerTask::runCount() const
{
	return m_count;
}

bool XQTimerTask::isAutoDelete() const
{
	return m_autoDelete;
}

QDateTime XQTimerTask::runTime() const
{
	return m_runTime;
}

qint64 XQTimerTask::timerSec() const
{
	return m_timerSec;
}

void XQTimerTask::setEnabled(bool enabled)
{
	m_enable = enabled;
}
void XQTimerTask::setMainThreadRun(bool main)
{
	m_mainThreadRun = main;
}
void XQTimerTask::runTask()
{
	if (m_upTimeFunc == nullptr)
		m_runTime = QDateTime::currentDateTime().addSecs(m_timerSec);//更新下一次执行时间
	else
		m_runTime = m_upTimeFunc(this);
	if (m_count > 0)
		m_count--;//更新次数
	if(m_task)
		m_task(this);
}

void XQTimerTask::setRunCount(qint64 count)
{
	m_count = count;
}

void XQTimerTask::setAutoDelete(bool dl)
{
	m_autoDelete = dl;
}

void XQTimerTask::setRunTime(QDateTime time)
{
	m_runTime = time;
}

void XQTimerTask::setTimerSec(qint64 sec)
{
	m_timerSec = sec;
}

void XQTimerTask::setUpTimeFunc(std::function<QDateTime(XQTimerTask*)> func)
{
	m_upTimeFunc = func;
}

void XQTimerTask::setTask(std::function<void()> task)
{
	m_task = [=](XQTimerTask*) {task(); };
}
void XQTimerTask::setTask(std::function<void(XQTimerTask*)> task)
{
	m_task = task;
}